 
  

 






<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> 
<html>

<!-- Mirrored from www.javapractices.com/topic/TopicAction.do?Id=56 by HTTrack Website Copier/3.x [XR&CO'2010], Sun, 12 Jun 2011 17:28:08 GMT -->
<!-- Added by HTTrack --><meta http-equiv="content-type" content="text/html;charset=UTF-8"><!-- /Added by HTTrack -->
<head>
 <title>
  Java Practices -> Generating unique IDs
 </title>
 <link rel="stylesheet" type="text/css" href="../stylesheet8.css" media="all">
 
 <link rel="shortcut icon" href='../images/favicon.ico' type="image/vnd.microsoft.icon">
 <meta name="description" content="Concise presentations of java programming practices, tasks, and conventions, amply illustrated with syntax highlighted code examples.">
 
 <meta name='keywords' content='unique,java,java programming,java practices,java idiom,java style,java design patterns,java coding conventions,'>
 
 
</head>
 
<body>


<div class='menu-bar'>
 
  <a href='../home/HomeAction.html' title='Table of Contents'>Home</a> |
  <a href='../vote/VoteSummaryAction-2.html' title='View Poll Results'>Poll</a> |
   
  <A href='../feedback/FeedbackAction451f-2.html?Operation=Show' title='Send Your Feedback'>Wiki</a> |
  <b><a href='../source/SourceAction-2.html' title='Grab Source Code'>Source Code</a></b><IMG class='no-margin' SRC="../images/goldstar.gif" ALT=""> |

  <a href='http://www.web4j.com/Java_Web_Application_Framework_Overview.jsp?From=1' title='Free Download - Java Web Application Framework'><b>WEB4J</b></a> |
  
  <a href='http://www.date4j.net/' title='Replacement for java.util.Date'><b>DATE4J</b></a> |

   <a href='../references/ReferencesAction-2.html' title='References'>Links</a>
   
  <form action='http://www.javapractices.com/search/SearchAction.do' method='get' class='search-form'>
   <input type='text' name='SearchTerms' value="" size=12 maxlength=50 class='search'>
   <input type='submit' value="Search">
  </form>
 
</div>

<P>



  

 






<p class="display-messages">

 

 

</p>


<div class="main-layout">
 
   

 




<div class='page-title'>Generating unique IDs</div>

<div class='main-body'>
 
<br>When identifiers are used solely within a database, their generation
should be left to the database itself. (See <tt><a href="http://java.sun.com/javase/6/docs/api/java/sql/Statement.html#getGeneratedKeys()">Statement.getGeneratedKeys</a></tt>.)

<p>Unique identifiers which are "published" in some way may need special
treatment, since the identifier may need to be difficult to guess or forge.
A typical example is the value of a cookie used as a session identifier
- simply using a series of consecutive integers is generally unacceptable,
since one user could easily impersonate another by altering the value of
the cookie to some nearby integer.

<h3>Style 1 - UUID</h3>
When Java 5 is available, the 
<a href='http://java.sun.com/javase/6/docs/api/java/util/UUID.html'>UUID</a> 
class provides a simple means for generating
unique ids. The identifiers generated by UUID are actually <em>universally</em>
unique identifiers.

<P><b>Example</b>
<br>
<PRE>

<span class='keyword'>import</span> java.util.UUID;

<span class='keyword'>public</span> <span class='keyword'>class</span> GenerateUUID {
  
  <span class='keyword'>public</span> <span class='keyword'>static</span> <span class='keyword'>final</span> <span class='keyword'>void</span> main(String... aArgs){
    <span class='comment'>//generate random UUIDs
</span>    UUID idOne = UUID.randomUUID();
    UUID idTwo = UUID.randomUUID();
    log(<span class='literal'>"UUID One: "</span> + idOne);
    log(<span class='literal'>"UUID Two: "</span> + idTwo);
  }
  
  <span class='keyword'>private</span> <span class='keyword'>static</span> <span class='keyword'>void</span> log(Object aObject){
    System.out.println( String.valueOf(aObject) );
  }
} 
</PRE>
<br>
<br>Example run :
<PRE>
>java -cp . GenerateUUID
UUID One: 067e6162-3b6f-4ae2-a171-2470b63dff00 
UUID Two: 54947df8-0e9e-4471-a2f9-9af509fb5889
</PRE>

<p><em>If Java 5 is not available</em>, then there are other more laborious ways to generate unique ids (see below).

<h3>Style 2 - SecureRandom and MessageDigest</h3>
<P>The following method uses <tt>SecureRandom</tt> and <tt>MessageDigest</tt> :
<ul>
<li>
upon startup, initialize <tt><a href="http://java.sun.com/javase/6/docs/api/java/security/SecureRandom.html">SecureRandom</a></tt>
(this may be a lengthy operation)</li>

<li>
when a new identifier is needed, generate a random number using <tt>SecureRandom</tt></li>

<li>
create a <tt><a href="http://java.sun.com/javase/6/docs/api/java/security/MessageDigest.html">MessageDigest</a></tt>
of the random number</li>

<li>
encode the <tt>byte[]</tt> returned by the <tt>MessageDigest</tt> into
some acceptable textual form</li>

<li>
check if the result is already being used ; if it is not already taken,
it is suitable as a unique identifier</li>
</ul>
The <tt>MessageDigest</tt> class is suitable for generating a "one-way
hash" of&nbsp; arbitrary data. (Note that hash values never uniquely identify
their source data, since different source data can produce the same hash
value. The value of <tt>hashCode</tt>, for example, does not uniquely identify
its associated object.) A <tt>MessageDigest</tt> takes any input, and produces
a <tt>String</tt> which :
<ul>
<li>
is of fixed length</li>

<li>
does not allow the original input to be easily recovered (in fact, this
is very hard)</li>

<li>
does not uniquely identify the input ; however, similar input will produce
dissimilar message digests</li>
</ul>
<tt>MessageDigest</tt> is often used as a checksum, for verifying that
data has not been altered since its creation.

<p><b>Example</b>
<br>
<PRE>

<span class='keyword'>import</span> java.security.SecureRandom;
<span class='keyword'>import</span> java.security.MessageDigest;
<span class='keyword'>import</span> java.security.NoSuchAlgorithmException;

<span class='keyword'>public</span> <span class='keyword'>class</span> GenerateId {

  <span class='keyword'>public</span> <span class='keyword'>static</span> <span class='keyword'>void</span> main (String... arguments) {
    <span class='keyword'>try</span> {
      <span class='comment'>//Initialize SecureRandom
</span>      <span class='comment'>//This is a lengthy operation, to be done only upon
</span>      <span class='comment'>//initialization of the application
</span>      SecureRandom prng = SecureRandom.getInstance(<span class='literal'>"SHA1PRNG"</span>);

      <span class='comment'>//generate a random number
</span>      String randomNum = <span class='keyword'>new</span> Integer( prng.nextInt() ).toString();

      <span class='comment'>//get its digest
</span>      MessageDigest sha = MessageDigest.getInstance(<span class='literal'>"SHA-1"</span>);
      <span class='keyword'>byte</span>[] result =  sha.digest( randomNum.getBytes() );

      System.out.println(<span class='literal'>"Random number: "</span> + randomNum);
      System.out.println(<span class='literal'>"Message digest: "</span> + hexEncode(result) );
    }
    <span class='keyword'>catch</span> ( NoSuchAlgorithmException ex ) {
      System.err.println(ex);
    }
  }

  <span class='comment'>/**
  * The byte[] returned by MessageDigest does not have a nice
  * textual representation, so some form of encoding is usually performed.
  *
  * This implementation follows the example of David Flanagan's book
  * "Java In A Nutshell", and converts a byte array into a String
  * of hex characters.
  *
  * Another popular alternative is to use a "Base64" encoding.
  */</span>
  <span class='keyword'>static</span> <span class='keyword'>private</span> String hexEncode( <span class='keyword'>byte</span>[] aInput){
    StringBuilder result = <span class='keyword'>new</span> StringBuilder();
    <span class='keyword'>char</span>[] digits = {<span class='literal'>'0'</span>, <span class='literal'>'1'</span>, <span class='literal'>'2'</span>, <span class='literal'>'3'</span>, <span class='literal'>'4'</span>,<span class='literal'>'5'</span>,<span class='literal'>'6'</span>,<span class='literal'>'7'</span>,<span class='literal'>'8'</span>,<span class='literal'>'9'</span>,<span class='literal'>'a'</span>,<span class='literal'>'b'</span>,<span class='literal'>'c'</span>,<span class='literal'>'d'</span>,<span class='literal'>'e'</span>,<span class='literal'>'f'</span>};
    <span class='keyword'>for</span> ( <span class='keyword'>int</span> idx = <span class='literal'>0</span>; idx &lt; aInput.length; ++idx) {
      <span class='keyword'>byte</span> b = aInput[idx];
      result.append( digits[ (b&amp;<span class='literal'>0xf0</span>) &gt;&gt; <span class='literal'>4</span> ] );
      result.append( digits[ b&amp;<span class='literal'>0x0f</span>] );
    }
    <span class='keyword'>return</span> result.toString();
  }
} 
</PRE>
<br>
<br>Example run :

<p><tt>>java -cp . GenerateId</tt>
<br><tt>Random number: -1103747470</tt>
<br><tt>Message digest: c8fff94ba996411079d7114e698b53bac8f7b037</tt>

<h3>Style 3 - UID</h3>
Finally, here is another method, using a <tt><a href="http://java.sun.com/javase/6/docs/api/java/rmi/server/UID.html">java.rmi.server.UID</a></tt>.
The <tt>Serializable</tt> identifiers generated by this class are unique
on the host on which they are generated, provided that
<ul>
<li>the host takes more than one millisecond to reboot</li>
<li>the host's clock is never set to run backwards</li>
</ul>
In order to construct a <tt>UID</tt> that is globally unique, simply pair
a <tt>UID</tt> with an <tt><a href="http://java.sun.com/javase/6/docs/api/java/net/InetAddress.html">InetAddress</a></tt>.

<p><b>Example</b>
<br>
<PRE>

<span class='keyword'>import</span> java.rmi.server.UID;

<span class='keyword'>public</span> <span class='keyword'>class</span> UniqueId {

  <span class='comment'>/**
  * Build and display some UID objects.
  */</span>
  <span class='keyword'>public</span> <span class='keyword'>static</span> <span class='keyword'>void</span> main (String... arguments) {
    <span class='keyword'>for</span> (<span class='keyword'>int</span> idx=<span class='literal'>0</span>; idx&lt;<span class='literal'>10</span>; ++idx){
      UID userId = <span class='keyword'>new</span> UID();
      System.out.println(<span class='literal'>"User Id: "</span> + userId);
    }
  }
} 
</PRE>
<br>
<p>Example run :
<p><tt>User Id: 3179c3:ec6e28a7ef:-8000</tt>
<br><tt>User Id: 3179c3:ec6e28a7ef:-7fff</tt>
<br><tt>User Id: 3179c3:ec6e28a7ef:-7ffe</tt>
<br><tt>User Id: 3179c3:ec6e28a7ef:-7ffd</tt>
<br><tt>User Id: 3179c3:ec6e28a7ef:-7ffc</tt>
<br><tt>User Id: 3179c3:ec6e28a7ef:-7ffb</tt>
<br><tt>User Id: 3179c3:ec6e28a7ef:-7ffa</tt>
<br><tt>User Id: 3179c3:ec6e28a7ef:-7ff9</tt>
<br><tt>User Id: 3179c3:ec6e28a7ef:-7ff8</tt>
<br><tt>User Id: 3179c3:ec6e28a7ef:-7ff7</tt>

<p>Clearly, these are not secure identifiers - knowing one, it is easy
to guess another.
<br>
<br>

</div>





<div class='topic-section'>Would you use this technique?</div>
<div class='main-body'>
  
  <form action="http://www.javapractices.com/vote/AddVoteAction.do" method='post'>
    Yes<input type='radio' name='Choice' value='Y' >
    &nbsp;&nbsp;No<input type='radio' name='Choice' value='N'>
    &nbsp;&nbsp;Undecided<input type='radio' name='Choice' value="?" >
    &nbsp;&nbsp;<input type=submit value="Vote" >
    <input type='hidden' name='Operation' value='Apply'>
    <input type='hidden' name='TopicId' value='56'>
  </form>
</div>

<div style='height:10.0em;'></div>

 
 
</div>

  

 





<div align='center' class='legalese'>  
&copy; 2011 Hirondelle Systems |
<a href='../source/SourceAction-2.html'><b>Source Code</b></a><IMG class='no-margin' SRC="../images/goldstar.gif" ALT=""> |
<a href="mailto:webmaster@javapractices.com">Contact</a> |
<a href="http://creativecommons.org/licenses/by-nc-sa/1.0/">License</a> |
<a href='../apps/cjp.rss'>RSS</a>
<!-- ukey="2AC36CD2" -->
<!-- ckey="16DF3D87" -->
<br>

 Individual code snippets can be used under this <a href='../LICENSE.txt'>BSD license</a> - Last updated on June 6, 2010.<br>
 Over 150,000 unique IPs last month - <span title='Java Practices 2.6.5, Mon May 16 00:00:00 EDT 2011'>Built with</span> <a href='http://www.web4j.com/'>WEB4J</a>.<br>
 - In Memoriam : Bill Dirani -
</div>

<script src="../../www.google-analytics.com/urchin.js" type="text/javascript">
</script>
<script type="text/javascript">
_uacct = "UA-2633428-1";
urchinTracker();
</script>



</body>

<!-- Mirrored from www.javapractices.com/topic/TopicAction.do?Id=56 by HTTrack Website Copier/3.x [XR&CO'2010], Sun, 12 Jun 2011 17:28:08 GMT -->
<!-- Added by HTTrack --><meta http-equiv="content-type" content="text/html;charset=UTF-8"><!-- /Added by HTTrack -->
</html>
